//
//  HWNetWorkManager.m
//  嗨文
//
//  Created by 响当当 on 2019/1/8.
//  Copyright © 2019年 dongzheng. All rights reserved.
//

#import "HWNetWorkManager.h"

typedef enum REQUESTSTATUS
{
    REQUESTSTATUS_SUCESS = 200, //请求成功
    REQUESTSTATUS_FAILL = 404, //未找到
    REQUESTSTATUS_FAILLD = 400, //请求失败
    REQUESTSTATUS_SERVER_ERROR = 500, //服务器异常
    
} REQUESTSTATUS;

typedef enum HWNetWorkRequestType
{
    
    RequestType_Get = 0,
    RequestType_Post = 1,
    RequestType_ImgFormData = 2,
    RequestType_JsonPost = 3
    
} HWNetWorkRequestType;

static HWNetWorkManager *manager = nil;
//默认网络请求时间
static const NSUInteger kDefaultTimeoutInterval = 15;

@interface HWNetWorkManager()
@property (nonatomic,strong) AFHTTPSessionManager *httpManager;
@property (nonatomic,strong) AFURLSessionManager *jsonManager;
@property (nonatomic,assign) BOOL isTokenExpire;    //判断token是否过期
@property (nonatomic,assign) BOOL isLocked;    //用于锁定过期token网络多次请求
@property (nonatomic,assign) BOOL isAlertShowing;    //正在提示
@property (nonatomic,assign) HWNetWorkRequestType requestType;
@property (nonatomic,copy) NSString *currentRequestUrl;
@property (nonatomic,strong) NSDictionary *currentPrarmers;
@end

@implementation HWNetWorkManager
+ (HWNetWorkManager *)netWorkManager
{
    @synchronized (manager) {
        if (!manager) {
            manager = [[HWNetWorkManager alloc]init];
            
            manager.isTokenExpire = false;
            manager.isAlertShowing = false;
#pragma  开始配置普通请求
            manager.httpManager = [AFHTTPSessionManager manager];
            manager.httpManager.requestSerializer.timeoutInterval = kDefaultTimeoutInterval; //默认网络请求时间
            manager.httpManager.responseSerializer = [AFJSONResponseSerializer serializer];

            //申明返回的结果是json类型
            manager.httpManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"application/xml",@"text/plain",@"application/xhtml+xml", @"text/json",@"multipart/form-data", @"text/javascript",@"text/html", @"text/xml",                                                      @"image/jpeg",@"image/png",@"application/x-www-form-urlencoded", nil];
#pragma   结束配置普通请求
            
#pragma 开始配置json
            manager.jsonManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            //            manager.requestSerializer.timeoutInterval = kDefaultTimeoutInterval; //默认网络请求时间
            
            NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"" parameters:nil error:nil];
            request.timeoutInterval= kDefaultTimeoutInterval;
            [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
            // 设置body
            //            [request setHTTPBody:JSONdata];
            AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
            
            responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"application/xml",@"text/plain",@"application/xhtml+xml", @"text/json",@"multipart/form-data", @"text/javascript",@"text/html", @"text/xml",                                                      @"image/jpeg",@"image/png",@"application/x-www-form-urlencoded", nil];
            manager.jsonManager.responseSerializer  = responseSerializer;
#pragma  结束配置json
        }
    }
    return manager;
}

- (void)monitorNetworking
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                
                [HWUtilties showAlertWithTitle:@"提示" content:@"暂无识别开启网络，是否前往设置" buttonTitle:@"确定" ConfirmWithBlock:^{
                    [HWUtilties openUrlSchedule:UIApplicationOpenSettingsURLString];
                }];
                break;
            case AFNetworkReachabilityStatusNotReachable:
                [HWUtilties showAlertWithTitle:@"提示" content:@"暂无识别网络，是否前往设置" buttonTitle:@"确定" ConfirmWithBlock:^{
                    [HWUtilties openUrlSchedule:UIApplicationOpenSettingsURLString];
                }];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                NSLog(@"GPRS网络");
            }
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                NSLog(@"wifi网络");
            }
                break;
            default:
                break;
        }
    }];
}
//
- (void)getRequestUrl:(NSString *)urlStr
         withPramater:(NSDictionary *)pramater
               sucess:(RequsetSuccess)sucessCallBack
              failure:(RequsetFailure)failureCallBack
{
    [self sendNetWorkWithRequestType:RequestType_Get url:urlStr withPramater:pramater sucess:sucessCallBack failure:failureCallBack];
}
#pragma http post
- (void)postRequestUrl:(NSString *)urlStr
          withPramater:(id)pramater
                sucess:(RequsetSuccess)sucessCallBack
               failure:(RequsetFailure)failureCallBack
{
    [self sendNetWorkWithRequestType:RequestType_Post url:urlStr withPramater:pramater sucess:sucessCallBack failure:failureCallBack];
}


#pragma json post
- (void)postJsonRequest:(NSString *)urlStr
           withPramater:(NSDictionary *)pramater
                 sucess:(RequsetSuccess)sucessCallBack
                failure:(RequsetFailure)failureCallBack
{
    [self sendNetWorkWithRequestType:RequestType_JsonPost url:urlStr withPramater:pramater sucess:sucessCallBack failure:failureCallBack];
}

//- (void)postImgWithUrl:(NSString *)urlStr
//                   img:(NSArray *)imglist
//               imgType:(IMGTYPE)imgtype
//          withPramater:(NSDictionary *)pramater
//                sucess:(RequsetSuccess)sucessCallBack
//               failure:(RequsetFailure)failureCallBack
//{
//
//    [self.httpManager POST:urlStr parameters:pramater constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
//     {
//
//         [imglist enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//             if (imgtype  == IMGTYPE_JPG)
//             {
//                 NSData *data = UIImageJPEGRepresentation(obj,0.1);
//                 [formData appendPartWithFileData:data name:@"file" fileName:@"auge.jpg" mimeType:@"image/jpeg"];
//             }
//             if(imgtype == IMGTYPE_PNG)
//             {
//                 NSData *data = UIImagePNGRepresentation(obj);
//                 [formData appendPartWithFileData:data name:@"file" fileName:@"auge.png" mimeType:@"image/png"];
//             }
//         }];
//
//     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject)
//     {
//         sucessCallBack(responseObject);
//     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
//     {
//         [self failRequestWithError:error fail:failureCallBack];
//     }];
//}
#pragma -mark 发送网络请求
- (void)sendNetWorkWithRequestType:(HWNetWorkRequestType)requestType
                               url:(NSString *)urlStr
                      withPramater:(NSDictionary *)pramater
                            sucess:(RequsetSuccess)sucessCallBack
                           failure:(RequsetFailure)failureCallBack
{
    WeakSelf(weakSelf)
    
    _requestType = requestType;
    _currentPrarmers = pramater;
    _currentRequestUrl = urlStr;
    if (requestType == RequestType_Get)
    {
        [self.httpManager GET:urlStr parameters:pramater success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            [weakSelf sucessFucWithresponseObject:responseObject callBack:sucessCallBack];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [weakSelf failRequestWithError:error fail:failureCallBack];
        }];
        
    }else if (requestType == RequestType_Post)
    {
        [self.httpManager POST:urlStr parameters:pramater success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            [weakSelf sucessFucWithresponseObject:responseObject callBack:sucessCallBack];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DISMISS_VP(1.f);
            [weakSelf failRequestWithError:error fail:failureCallBack];
        }];
    }else if (requestType == RequestType_JsonPost)
    {
        NSData *JSONdata = [NSData data];
        JSONdata = [[HWUtilties toJSONString:pramater] dataUsingEncoding:NSUTF8StringEncoding];
        NSString *url =[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];
        request.timeoutInterval= kDefaultTimeoutInterval;
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        // 设置body
        [request setHTTPBody:JSONdata];
        [[self.jsonManager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if (!error) {
                id jsonData = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
                [weakSelf sucessFucWithresponseObject:jsonData callBack:sucessCallBack];
            } else {
                [weakSelf failRequestWithError:error fail:failureCallBack];
            }
        }] resume];
    }
}
#pragma -mark 成功请求回调
- (void)sucessFucWithresponseObject:(id)responseObject callBack:(RequsetSuccess)sucessCallBack
{
    NSNumber *code;
    if([responseObject[@"message"] isEqualToString:@"SUCCESS"])
    {
        code = @200;
    }
    else if([responseObject[@"message"] isEqualToString:@"access_token 已失效!"])
    {
        sucessCallBack(responseObject);
        return;
    }else if([responseObject[@"message"] isEqualToString:@"书币不足，请充值"])
    {
        sucessCallBack(responseObject);
    }
    else
    {
        code = responseObject[@"code"];
    }
    
    NSString *message = responseObject[@"message"];
    switch ([code intValue]) {
        case REQUESTSTATUS_SUCESS:
            sucessCallBack(responseObject);
            break;
        case REQUESTSTATUS_FAILL | REQUESTSTATUS_SERVER_ERROR :
//            [SVProgressHUD showErrorWithStatus:@"网络不给力 请稍后再试"];
            DISMISS_VP(1.f);
            break;
//        case REQUESTSTATUS_MUTALLOGIN: //账号被顶
//            [SVProgressHUD showErrorWithStatus:@"该账号已在别出登录"];
//            DISMISS_SVP(1.f);
//            break;
//        case REQUESTSTATUS_TOKENNULL:  //没有token
//            expireRequsetRCallBack = sucessCallBack;
//            self.isTokenExpire = true;
//        case REQUESTSTATUS_TOKENEXPRICE:  //token过期
//            expireRequsetRCallBack = sucessCallBack;
//            self.isTokenExpire = true;
//            break;
//        case REQUESTSTATUS_VIPEXPRIC:    //会员过期
//            [[Utilties getCurrentVC].navigationController popViewControllerAnimated:false];
//            [Utilties pushWebWithUrl:kExpireVipAlterUrl title:@"温馨提示"];
//            break;
//        case REQUESTSTATUS_NOPayRecord: //未充值
//            [[Utilties getCurrentVC].navigationController popViewControllerAnimated:false];
//            [Utilties pushWebWithUrl:kNoVipAlterUrl title:@"温馨提示"];
//            break;
        default:
            [SVProgressHUD showErrorWithStatus:message];
            DISMISS_VP(1.f);
            break;
    }
}

#pragma -mark 失败请求回调
- (void)failRequestWithError:(NSError *)error fail:(RequsetFailure)failureCallBack
{
    //    if (!_isAlertShowing) {
    //        if (error.code  == 500) {
    //            _isAlertShowing = true;
    //            [Utilties showAlertWithTitle:@"提示" content:@"服务器错误，请退出应用重试..." buttonTitle:@"确定" ConfirmWithBlock:^{
    //                _isAlertShowing = false;
    //            }];
    //        }else if (error.code  == -1001)
    //        {
    //            _isAlertShowing = true;
    //            [Utilties showAlertWithTitle:@"提示" content:@"4G网络响应超时，请退出应用切换网络再试..." buttonTitle:@"确定" ConfirmWithBlock:^{
    //                _isAlertShowing = false;
    //            }];
    //        }else if (error.code  == -1005)
    //        {
    //            _isAlertShowing = true;
    //            [Utilties showAlertWithTitle:@"提示" content:@"无线网络响应超时，请退出应用切换网络再试..." buttonTitle:@"确定" ConfirmWithBlock:^{
    //                _isAlertShowing = false;
    //            }];
    //        }
    //    }
    failureCallBack(error);
}
//#pragma -mark 设置token是否过期
//- (void)setIsTokenExpire:(BOOL)isTokenExpire
//{
//    _isTokenExpire = isTokenExpire;
//    if (!_isLocked) {
//        if (_isTokenExpire) {
//            _isLocked = true;
//            WeakSelf(weakSelf);
//            [LCAutoRefreshTokenManager refreshTokenSucess:^{
//
//                [weakSelf sendNetWorkWithRequestType:weakSelf.requestType url:weakSelf.currentRequestUrl withPramater:weakSelf.currentPrarmers sucess:^(id responseObject) {
//
//                    _isTokenExpire = false;
//                    _isLocked = false;   //取消锁定
//                    //如果走errorcode就执行
//                    if (expireRequsetRCallBack) {
//                        expireRequsetRCallBack(responseObject);
//                    }
//
//                } failure:^(NSError *error) {
//
//                    _isLocked = false;  //取消锁定
//                    _isTokenExpire = false;
//
//                }];
//
//            } fail:^(NSError *error) {
//                _isLocked = false;  //取消锁定
//                _isTokenExpire = false;
//            }];
//        }
//    }
//}


- (void)postImgWithUrl:(NSString *)urlStr
                   img:(NSArray *)imglist
               imgType:(IMGTYPE)imgtype
          withPramater:(NSDictionary *)pramater
                sucess:(RequsetSuccess)sucessCallBack
               failure:(RequsetFailure)failureCallBack
{
    
    [self.httpManager POST:urlStr parameters:pramater constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
         
         [imglist enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
             if (imgtype  == IMGTYPE_JPG)
             {
                 NSData *data = UIImageJPEGRepresentation(obj,0.1);
                 [formData appendPartWithFileData:data name:@"file" fileName:@"auge.jpg" mimeType:@"image/jpeg"];
             }
             if(imgtype == IMGTYPE_PNG)
             {
                 NSData *data = UIImagePNGRepresentation(obj);
                 [formData appendPartWithFileData:data name:@"file" fileName:@"auge.png" mimeType:@"image/png"];
             }
         }];
         
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject)
     {
         sucessCallBack(responseObject);
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
     {
         [self failRequestWithError:error fail:failureCallBack];
     }];
}

@end

